using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using System.Text.Json;
using System.Collections.Concurrent;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 智能内容推荐引擎 - 基于用户行为和内容分析的个性化推荐系统
    /// </summary>
    public interface IIntelligentRecommendationEngine
    {
        Task<List<ContentRecommendation>> GetRecommendationsAsync(string userId, RecommendationContext context);
        Task<List<TemplateRecommendation>> RecommendTemplatesAsync(string userId, string contentType);
        Task<List<StyleRecommendation>> RecommendWritingStylesAsync(string userId, string currentContent);
        Task<List<ResourceRecommendation>> RecommendResourcesAsync(string userId, string projectId);
        Task<List<CollaboratorRecommendation>> RecommendCollaboratorsAsync(string userId, string projectId);
        Task RecordUserInteractionAsync(UserInteraction interaction);
        Task<UserPreferenceProfile> GetUserPreferenceProfileAsync(string userId);
        Task UpdateUserPreferencesAsync(string userId, Dictionary<string, object> preferences);
        Task<List<TrendingContent>> GetTrendingContentAsync(string category, TimeSpan timeRange);
    }

    public class IntelligentRecommendationEngine : IIntelligentRecommendationEngine
    {
        private readonly ILogger<IntelligentRecommendationEngine> _logger;
        private readonly IAIService _aiService;
        private readonly IVectorService _vectorService;
        private readonly IDataStorageService _dataStorage;
        private readonly ConcurrentDictionary<string, UserBehaviorTracker> _userTrackers = new();

        public IntelligentRecommendationEngine(
            ILogger<IntelligentRecommendationEngine> logger,
            IAIService aiService,
            IVectorService vectorService,
            IDataStorageService dataStorage)
        {
            _logger = logger;
            _aiService = aiService;
            _vectorService = vectorService;
            _dataStorage = dataStorage;
        }

        /// <summary>
        /// 获取个性化内容推荐
        /// </summary>
        public async Task<List<ContentRecommendation>> GetRecommendationsAsync(string userId, RecommendationContext context)
        {
            try
            {
                _logger.LogInformation($"生成内容推荐: 用户 {userId}");

                var recommendations = new List<ContentRecommendation>();

                // 获取用户偏好档案
                var userProfile = await GetUserPreferenceProfileAsync(userId);

                // 基于内容的推荐
                var contentBasedRecs = await GetContentBasedRecommendationsAsync(userId, context, userProfile);
                recommendations.AddRange(contentBasedRecs);

                // 协同过滤推荐
                var collaborativeRecs = await GetCollaborativeFilteringRecommendationsAsync(userId, context, userProfile);
                recommendations.AddRange(collaborativeRecs);

                // 基于知识图谱的推荐
                var knowledgeBasedRecs = await GetKnowledgeBasedRecommendationsAsync(userId, context, userProfile);
                recommendations.AddRange(knowledgeBasedRecs);

                // AI增强推荐
                var aiEnhancedRecs = await GetAIEnhancedRecommendationsAsync(userId, context, userProfile);
                recommendations.AddRange(aiEnhancedRecs);

                // 排序和去重
                recommendations = await RankAndDeduplicateRecommendationsAsync(recommendations, userProfile);

                _logger.LogInformation($"生成了 {recommendations.Count} 个推荐");
                return recommendations.Take(context.MaxRecommendations).ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"生成内容推荐失败: 用户 {userId}");
                return new List<ContentRecommendation>();
            }
        }

        /// <summary>
        /// 推荐模板
        /// </summary>
        public async Task<List<TemplateRecommendation>> RecommendTemplatesAsync(string userId, string contentType)
        {
            try
            {
                var userProfile = await GetUserPreferenceProfileAsync(userId);
                var templates = new List<TemplateRecommendation>();

                // 基于用户历史使用的模板推荐
                var historicalTemplates = await GetHistoricalTemplateUsageAsync(userId, contentType);
                
                // 基于相似用户的模板推荐
                var similarUserTemplates = await GetSimilarUserTemplatesAsync(userId, contentType);

                // 基于内容类型的热门模板
                var popularTemplates = await GetPopularTemplatesAsync(contentType);

                // AI生成的个性化模板建议
                var aiTemplates = await GenerateAITemplateRecommendationsAsync(userId, contentType, userProfile);

                templates.AddRange(historicalTemplates);
                templates.AddRange(similarUserTemplates);
                templates.AddRange(popularTemplates);
                templates.AddRange(aiTemplates);

                return await RankTemplateRecommendationsAsync(templates, userProfile);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"推荐模板失败: 用户 {userId}, 类型 {contentType}");
                return new List<TemplateRecommendation>();
            }
        }

        /// <summary>
        /// 推荐写作风格
        /// </summary>
        public async Task<List<StyleRecommendation>> RecommendWritingStylesAsync(string userId, string currentContent)
        {
            try
            {
                var userProfile = await GetUserPreferenceProfileAsync(userId);
                var recommendations = new List<StyleRecommendation>();

                // 分析当前内容的风格
                var currentStyle = await AnalyzeContentStyleAsync(currentContent);

                // 基于用户偏好推荐风格
                var preferredStyles = await GetPreferredStylesAsync(userId, userProfile);

                // 基于内容类型推荐适合的风格
                var contextualStyles = await GetContextualStylesAsync(currentContent, currentStyle);

                // AI建议的风格改进
                var aiStyleSuggestions = await GetAIStyleSuggestionsAsync(currentContent, userProfile);

                recommendations.AddRange(preferredStyles);
                recommendations.AddRange(contextualStyles);
                recommendations.AddRange(aiStyleSuggestions);

                return await RankStyleRecommendationsAsync(recommendations, userProfile, currentStyle);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"推荐写作风格失败: 用户 {userId}");
                return new List<StyleRecommendation>();
            }
        }

        /// <summary>
        /// 推荐相关资源
        /// </summary>
        public async Task<List<ResourceRecommendation>> RecommendResourcesAsync(string userId, string projectId)
        {
            try
            {
                var recommendations = new List<ResourceRecommendation>();

                // 获取项目上下文
                var projectContext = await GetProjectContextAsync(projectId);

                // 推荐相关文档
                var relatedDocs = await RecommendRelatedDocumentsAsync(projectId, projectContext);
                recommendations.AddRange(relatedDocs);

                // 推荐参考资料
                var references = await RecommendReferenceResourcesAsync(projectId, projectContext);
                recommendations.AddRange(references);

                // 推荐工具和插件
                var tools = await RecommendToolsAndPluginsAsync(userId, projectContext);
                recommendations.AddRange(tools);

                // 推荐学习资源
                var learningResources = await RecommendLearningResourcesAsync(userId, projectContext);
                recommendations.AddRange(learningResources);

                return await RankResourceRecommendationsAsync(recommendations, userId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"推荐资源失败: 用户 {userId}, 项目 {projectId}");
                return new List<ResourceRecommendation>();
            }
        }

        /// <summary>
        /// 推荐协作者
        /// </summary>
        public async Task<List<CollaboratorRecommendation>> RecommendCollaboratorsAsync(string userId, string projectId)
        {
            try
            {
                var recommendations = new List<CollaboratorRecommendation>();

                // 获取项目需求
                var projectRequirements = await AnalyzeProjectRequirementsAsync(projectId);

                // 基于技能匹配推荐
                var skillBasedRecs = await RecommendBySkillMatchAsync(projectRequirements);
                recommendations.AddRange(skillBasedRecs);

                // 基于历史协作推荐
                var historicalRecs = await RecommendByHistoricalCollaborationAsync(userId);
                recommendations.AddRange(historicalRecs);

                // 基于网络分析推荐
                var networkRecs = await RecommendByNetworkAnalysisAsync(userId, projectRequirements);
                recommendations.AddRange(networkRecs);

                return await RankCollaboratorRecommendationsAsync(recommendations, userId, projectId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"推荐协作者失败: 用户 {userId}, 项目 {projectId}");
                return new List<CollaboratorRecommendation>();
            }
        }

        /// <summary>
        /// 记录用户交互
        /// </summary>
        public async Task RecordUserInteractionAsync(UserInteraction interaction)
        {
            try
            {
                // 获取或创建用户行为跟踪器
                var tracker = _userTrackers.GetOrAdd(interaction.UserId, _ => new UserBehaviorTracker());
                
                // 记录交互
                tracker.RecordInteraction(interaction);

                // 异步保存到存储
                await SaveUserInteractionAsync(interaction);

                // 更新用户偏好
                await UpdateUserPreferencesFromInteractionAsync(interaction);

                _logger.LogDebug($"记录用户交互: {interaction.UserId} - {interaction.ActionType}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"记录用户交互失败: {interaction.UserId}");
            }
        }

        /// <summary>
        /// 获取用户偏好档案
        /// </summary>
        public async Task<UserPreferenceProfile> GetUserPreferenceProfileAsync(string userId)
        {
            try
            {
                var profileData = await _dataStorage.GetAsync<UserPreferenceProfile>($"user_profile_{userId}");
                if (profileData != null)
                {
                    return profileData;
                }

                // 创建新的用户档案
                var newProfile = await CreateUserProfileAsync(userId);
                await _dataStorage.SaveAsync($"user_profile_{userId}", newProfile);
                return newProfile;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取用户偏好档案失败: {userId}");
                return new UserPreferenceProfile { UserId = userId };
            }
        }

        /// <summary>
        /// 更新用户偏好
        /// </summary>
        public async Task UpdateUserPreferencesAsync(string userId, Dictionary<string, object> preferences)
        {
            try
            {
                var profile = await GetUserPreferenceProfileAsync(userId);
                
                foreach (var preference in preferences)
                {
                    profile.Preferences[preference.Key] = preference.Value;
                }

                profile.UpdatedAt = DateTime.Now;
                await _dataStorage.SaveAsync($"user_profile_{userId}", profile);

                _logger.LogInformation($"更新用户偏好: {userId}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新用户偏好失败: {userId}");
            }
        }

        /// <summary>
        /// 获取热门内容
        /// </summary>
        public async Task<List<TrendingContent>> GetTrendingContentAsync(string category, TimeSpan timeRange)
        {
            try
            {
                var endTime = DateTime.Now;
                var startTime = endTime.Subtract(timeRange);

                // 从数据存储中获取热门内容数据
                var trendingData = await _dataStorage.GetAsync<List<TrendingContent>>($"trending_{category}");
                
                if (trendingData == null)
                {
                    // 计算热门内容
                    trendingData = await CalculateTrendingContentAsync(category, startTime, endTime);
                    await _dataStorage.SaveAsync($"trending_{category}", trendingData, TimeSpan.FromHours(1));
                }

                return trendingData.Where(t => t.TrendingPeriod.Start >= startTime).ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取热门内容失败: {category}");
                return new List<TrendingContent>();
            }
        }

        #region 私有辅助方法

        private async Task<List<ContentRecommendation>> GetContentBasedRecommendationsAsync(
            string userId, RecommendationContext context, UserPreferenceProfile userProfile)
        {
            var recommendations = new List<ContentRecommendation>();

            // 基于用户历史内容的相似性推荐
            if (!string.IsNullOrEmpty(context.CurrentContent))
            {
                var similarContent = await _vectorService.SearchAsync(context.CurrentContent, "documents", 10);
                foreach (var content in similarContent)
                {
                    recommendations.Add(new ContentRecommendation
                    {
                        ContentId = content.Id,
                        Title = content.Content.Length > 50 ? content.Content.Substring(0, 50) + "..." : content.Content,
                        RecommendationType = RecommendationType.ContentBased,
                        Score = content.Score,
                        Reason = "基于当前内容的相似性"
                    });
                }
            }

            return recommendations;
        }

        private async Task<List<ContentRecommendation>> GetCollaborativeFilteringRecommendationsAsync(
            string userId, RecommendationContext context, UserPreferenceProfile userProfile)
        {
            var recommendations = new List<ContentRecommendation>();

            // 查找相似用户
            var similarUsers = await FindSimilarUsersAsync(userId, userProfile);

            // 基于相似用户的偏好推荐内容
            foreach (var similarUser in similarUsers.Take(5))
            {
                var userContent = await GetUserPreferredContentAsync(similarUser.UserId);
                foreach (var content in userContent.Take(3))
                {
                    recommendations.Add(new ContentRecommendation
                    {
                        ContentId = content.Id,
                        Title = content.Title,
                        RecommendationType = RecommendationType.Collaborative,
                        Score = content.Score * similarUser.SimilarityScore,
                        Reason = $"相似用户 {similarUser.UserId} 喜欢的内容"
                    });
                }
            }

            return recommendations;
        }

        private async Task<List<ContentRecommendation>> GetKnowledgeBasedRecommendationsAsync(
            string userId, RecommendationContext context, UserPreferenceProfile userProfile)
        {
            var recommendations = new List<ContentRecommendation>();

            // 基于知识图谱的推荐逻辑
            // 这里可以集成知识图谱数据库，如Neo4j
            await Task.Delay(10); // 占位符

            return recommendations;
        }

        private async Task<List<ContentRecommendation>> GetAIEnhancedRecommendationsAsync(
            string userId, RecommendationContext context, UserPreferenceProfile userProfile)
        {
            var recommendations = new List<ContentRecommendation>();

            try
            {
                var prompt = $@"
基于以下用户信息和上下文，推荐相关的创作内容：

用户偏好：{JsonSerializer.Serialize(userProfile.Preferences)}
当前内容类型：{context.ContentType}
项目上下文：{context.ProjectContext}

请推荐5个相关的创作主题或内容方向，格式如下：
1. 主题名称 - 推荐理由
2. 主题名称 - 推荐理由
...

推荐内容：";

                var aiResponse = await _aiService.GenerateTextAsync(prompt, 800, 0.7f);
                var aiRecommendations = ParseAIRecommendations(aiResponse);

                recommendations.AddRange(aiRecommendations);
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "AI增强推荐生成失败");
            }

            return recommendations;
        }

        private async Task<List<ContentRecommendation>> RankAndDeduplicateRecommendationsAsync(
            List<ContentRecommendation> recommendations, UserPreferenceProfile userProfile)
        {
            // 去重
            var uniqueRecommendations = recommendations
                .GroupBy(r => r.ContentId)
                .Select(g => g.OrderByDescending(r => r.Score).First())
                .ToList();

            // 根据用户偏好调整评分
            foreach (var rec in uniqueRecommendations)
            {
                rec.Score = AdjustScoreByUserPreferences(rec, userProfile);
            }

            // 排序
            return uniqueRecommendations.OrderByDescending(r => r.Score).ToList();
        }

        private float AdjustScoreByUserPreferences(ContentRecommendation recommendation, UserPreferenceProfile userProfile)
        {
            var adjustedScore = recommendation.Score;

            // 根据用户偏好调整评分
            if (userProfile.Preferences.ContainsKey("preferred_content_types"))
            {
                var preferredTypes = userProfile.Preferences["preferred_content_types"] as List<string>;
                if (preferredTypes?.Contains(recommendation.ContentType) == true)
                {
                    adjustedScore *= 1.2f;
                }
            }

            return Math.Min(adjustedScore, 1.0f);
        }

        private async Task<UserPreferenceProfile> CreateUserProfileAsync(string userId)
        {
            return new UserPreferenceProfile
            {
                UserId = userId,
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now,
                Preferences = new Dictionary<string, object>
                {
                    ["preferred_content_types"] = new List<string> { "article", "story", "report" },
                    ["preferred_writing_style"] = "professional",
                    ["preferred_length"] = "medium",
                    ["collaboration_preference"] = "moderate"
                }
            };
        }

        private async Task SaveUserInteractionAsync(UserInteraction interaction)
        {
            var key = $"interaction_{interaction.UserId}_{DateTime.Now:yyyyMM}";
            var interactions = await _dataStorage.GetAsync<List<UserInteraction>>(key) ?? new List<UserInteraction>();
            interactions.Add(interaction);
            await _dataStorage.SaveAsync(key, interactions);
        }

        private async Task UpdateUserPreferencesFromInteractionAsync(UserInteraction interaction)
        {
            // 基于用户交互更新偏好
            var profile = await GetUserPreferenceProfileAsync(interaction.UserId);
            
            // 更新内容类型偏好
            if (!string.IsNullOrEmpty(interaction.ContentType))
            {
                var contentTypes = profile.Preferences.GetValueOrDefault("preferred_content_types", new List<string>()) as List<string> ?? new List<string>();
                if (!contentTypes.Contains(interaction.ContentType))
                {
                    contentTypes.Add(interaction.ContentType);
                    profile.Preferences["preferred_content_types"] = contentTypes;
                }
            }

            await _dataStorage.SaveAsync($"user_profile_{interaction.UserId}", profile);
        }

        private List<ContentRecommendation> ParseAIRecommendations(string aiResponse)
        {
            var recommendations = new List<ContentRecommendation>();
            var lines = aiResponse.Split('\n', StringSplitOptions.RemoveEmptyEntries);

            foreach (var line in lines)
            {
                if (!string.IsNullOrEmpty(line.Trim()) && char.IsDigit(line.Trim()[0]))
                {
                    var parts = line.Split('-', 2);
                    if (parts.Length == 2)
                    {
                        recommendations.Add(new ContentRecommendation
                        {
                            ContentId = Guid.NewGuid().ToString(),
                            Title = parts[0].Trim().Substring(2), // 移除数字和点
                            RecommendationType = RecommendationType.AIGenerated,
                            Score = 0.8f,
                            Reason = parts[1].Trim()
                        });
                    }
                }
            }

            return recommendations;
        }

        private async Task<List<SimilarUser>> FindSimilarUsersAsync(string userId, UserPreferenceProfile userProfile)
        {
            // 简化的相似用户查找逻辑
            await Task.Delay(10);
            return new List<SimilarUser>();
        }

        private async Task<List<ContentItem>> GetUserPreferredContentAsync(string userId)
        {
            // 获取用户偏好的内容
            await Task.Delay(10);
            return new List<ContentItem>();
        }

        private async Task<List<TemplateRecommendation>> GetHistoricalTemplateUsageAsync(string userId, string contentType)
        {
            await Task.Delay(10);
            return new List<TemplateRecommendation>();
        }

        private async Task<List<TemplateRecommendation>> GetSimilarUserTemplatesAsync(string userId, string contentType)
        {
            await Task.Delay(10);
            return new List<TemplateRecommendation>();
        }

        private async Task<List<TemplateRecommendation>> GetPopularTemplatesAsync(string contentType)
        {
            await Task.Delay(10);
            return new List<TemplateRecommendation>();
        }

        private async Task<List<TemplateRecommendation>> GenerateAITemplateRecommendationsAsync(string userId, string contentType, UserPreferenceProfile userProfile)
        {
            await Task.Delay(10);
            return new List<TemplateRecommendation>();
        }

        private async Task<List<TemplateRecommendation>> RankTemplateRecommendationsAsync(List<TemplateRecommendation> templates, UserPreferenceProfile userProfile)
        {
            return templates.OrderByDescending(t => t.Score).ToList();
        }

        private async Task<ContentStyle> AnalyzeContentStyleAsync(string content)
        {
            await Task.Delay(10);
            return new ContentStyle { StyleName = "professional", Confidence = 0.8f };
        }

        private async Task<List<StyleRecommendation>> GetPreferredStylesAsync(string userId, UserPreferenceProfile userProfile)
        {
            await Task.Delay(10);
            return new List<StyleRecommendation>();
        }

        private async Task<List<StyleRecommendation>> GetContextualStylesAsync(string content, ContentStyle currentStyle)
        {
            await Task.Delay(10);
            return new List<StyleRecommendation>();
        }

        private async Task<List<StyleRecommendation>> GetAIStyleSuggestionsAsync(string content, UserPreferenceProfile userProfile)
        {
            await Task.Delay(10);
            return new List<StyleRecommendation>();
        }

        private async Task<List<StyleRecommendation>> RankStyleRecommendationsAsync(List<StyleRecommendation> recommendations, UserPreferenceProfile userProfile, ContentStyle currentStyle)
        {
            return recommendations.OrderByDescending(r => r.Score).ToList();
        }

        private async Task<ProjectContext> GetProjectContextAsync(string projectId)
        {
            await Task.Delay(10);
            return new ProjectContext { ProjectId = projectId };
        }

        private async Task<List<ResourceRecommendation>> RecommendRelatedDocumentsAsync(string projectId, ProjectContext context)
        {
            await Task.Delay(10);
            return new List<ResourceRecommendation>();
        }

        private async Task<List<ResourceRecommendation>> RecommendReferenceResourcesAsync(string projectId, ProjectContext context)
        {
            await Task.Delay(10);
            return new List<ResourceRecommendation>();
        }

        private async Task<List<ResourceRecommendation>> RecommendToolsAndPluginsAsync(string userId, ProjectContext context)
        {
            await Task.Delay(10);
            return new List<ResourceRecommendation>();
        }

        private async Task<List<ResourceRecommendation>> RecommendLearningResourcesAsync(string userId, ProjectContext context)
        {
            await Task.Delay(10);
            return new List<ResourceRecommendation>();
        }

        private async Task<List<ResourceRecommendation>> RankResourceRecommendationsAsync(List<ResourceRecommendation> recommendations, string userId)
        {
            return recommendations.OrderByDescending(r => r.Score).ToList();
        }

        private async Task<ProjectRequirements> AnalyzeProjectRequirementsAsync(string projectId)
        {
            await Task.Delay(10);
            return new ProjectRequirements { ProjectId = projectId };
        }

        private async Task<List<CollaboratorRecommendation>> RecommendBySkillMatchAsync(ProjectRequirements requirements)
        {
            await Task.Delay(10);
            return new List<CollaboratorRecommendation>();
        }

        private async Task<List<CollaboratorRecommendation>> RecommendByHistoricalCollaborationAsync(string userId)
        {
            await Task.Delay(10);
            return new List<CollaboratorRecommendation>();
        }

        private async Task<List<CollaboratorRecommendation>> RecommendByNetworkAnalysisAsync(string userId, ProjectRequirements requirements)
        {
            await Task.Delay(10);
            return new List<CollaboratorRecommendation>();
        }

        private async Task<List<CollaboratorRecommendation>> RankCollaboratorRecommendationsAsync(List<CollaboratorRecommendation> recommendations, string userId, string projectId)
        {
            return recommendations.OrderByDescending(r => r.Score).ToList();
        }

        private async Task<List<TrendingContent>> CalculateTrendingContentAsync(string category, DateTime startTime, DateTime endTime)
        {
            await Task.Delay(10);
            return new List<TrendingContent>();
        }

        #endregion
    }

    /// <summary>
    /// 用户行为跟踪器
    /// </summary>
    public class UserBehaviorTracker
    {
        private readonly List<UserInteraction> _interactions = new();
        private readonly object _lock = new();

        public void RecordInteraction(UserInteraction interaction)
        {
            lock (_lock)
            {
                _interactions.Add(interaction);
                
                // 保持最近1000个交互记录
                if (_interactions.Count > 1000)
                {
                    _interactions.RemoveAt(0);
                }
            }
        }

        public List<UserInteraction> GetRecentInteractions(TimeSpan timeRange)
        {
            lock (_lock)
            {
                var cutoff = DateTime.Now.Subtract(timeRange);
                return _interactions.Where(i => i.Timestamp > cutoff).ToList();
            }
        }
    }
}
